package com.剑指offer;

import java.util.ArrayList;
import java.util.LinkedList;

/*
 * 从上到下按层打印二叉树，同一层结点从左至右输出。每一层输出一行。
 * */
public class _60把二叉树打印成多行
{
    ArrayList<ArrayList<Integer>> Print(TreeNode_Number pRoot)
    {
        if (pRoot == null)
        {
            return null;
        }
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        LinkedList<TreeNode_Number> q = new LinkedList<>();
        ArrayList<Integer> temp = new ArrayList<>();
        q.add(pRoot);
        int now = 1, next = 0;
        while (!q.isEmpty())
        {
            TreeNode_Number node = q.remove();
            now--;
            temp.add(node.val);
            if (node.left != null)
            {
                q.add(node.left);
                next++;
            }
            if (node.right != null)
            {
                q.add(node.right);
                next++;
            }
            if (now == 0)
            {
                list.add(new ArrayList<>(temp));
                temp.clear();
                now = next;
                next = 0;
            }
        }
        return list;
    }

}
